<template>
  <div class="import-excel">
    <!-- 导入说明 -->
    <a-card class="instruction-card" :bordered="true">
      <template #title>
        <a-space>
          <icon-info-circle />
          <span>导入说明</span>
        </a-space>
      </template>
      
      <div class="instruction-content">
        <a-alert
          type="info"
          title="Excel文件格式要求"
          :show-icon="true"
          class="format-alert"
        >
          <div class="format-list">
            <a-descriptions :column="1" size="small" bordered>
              <a-descriptions-item label="章节编号">
                <a-tag color="blue">数字</a-tag>
                表示第几章（如：1, 2, 3）
              </a-descriptions-item>
              <a-descriptions-item label="问题编号">
                <a-tag color="green">数字</a-tag>
                表示章节内的问题顺序（如：1, 2, 3）
              </a-descriptions-item>
              <a-descriptions-item label="问题内容">
                <a-tag color="purple">文本</a-tag>
                问题或选项的具体内容
              </a-descriptions-item>
              <a-descriptions-item label="问题类型">
                <a-tag color="orange">T/C</a-tag>
                T表示系统文本，C表示用户选择选项
              </a-descriptions-item>
              <a-descriptions-item label="下一题编号">
                <a-tag color="red">数字</a-tag>
                用户选择后跳转的问题编号，0表示章节结束
              </a-descriptions-item>
              <a-descriptions-item label="需要输入框">
                <a-tag color="cyan">0/1</a-tag>
                1表示需要输入框，0或空表示不需要（可选）
              </a-descriptions-item>
              <a-descriptions-item label="图片路径">
                <a-tag color="gold">文本</a-tag>
                格式：/images/文件名.png
              </a-descriptions-item>
              <a-descriptions-item label="计时器">
                <a-tag color="pinkpurple">数字</a-tag>
                倒计时秒数，时间到自动跳转（可选）
              </a-descriptions-item>
            </a-descriptions>
          </div>
        </a-alert>
        
        <a-divider orientation="left">
          <icon-file />
          示例数据
        </a-divider>
        
        <div class="sample-section">
          <a-table 
            :data="sampleData" 
            :pagination="false" 
            size="small"
            :bordered="true"
            stripe
          >
            <template #columns>
              <a-table-column title="章节编号" data-index="chapter" :width="100" align="center" />
              <a-table-column title="问题编号" data-index="question" :width="100" align="center" />
              <a-table-column title="问题内容" data-index="content" />
              <a-table-column title="问题类型" data-index="type" :width="100" align="center">
                <template #cell="{ record }">
                  <a-tag :color="record.type === 'T' ? 'blue' : 'green'">
                    {{ record.type }}
                  </a-tag>
                </template>
              </a-table-column>
              <a-table-column title="下一题编号" data-index="next" :width="120" align="center" />
              <a-table-column title="需要输入框" data-index="needInput" :width="120" align="center">
                <template #cell="{ record }">
                  <a-tag :color="record.needInput ? 'cyan' : 'gray'">
                    {{ record.needInput || 0 }}
                  </a-tag>
                </template>
              </a-table-column>
              <a-table-column title="图片路径" data-index="img" :width="150" align="center">
                <template #cell="{ record }">
                  <span>{{ record.img || '-' }}</span>
                </template>
              </a-table-column>
              <a-table-column title="计时器" data-index="timer" :width="100" align="center">
                <template #cell="{ record }">
                  <span>{{ record.timer || '-' }}</span>
                </template>
              </a-table-column>
            </template>
          </a-table>
        </div>
        
        <a-divider />
        
        <div class="download-section">
          <a-button type="outline" size="large" @click="downloadTemplate">
            <template #icon>
              <IconDownload />
            </template>
            下载Excel模板
          </a-button>
        </div>
      </div>
    </a-card>
    
    <!-- 数据操作 -->
    <a-card class="operation-card" :bordered="true">
      <template #title>
        <a-space>
          <icon-settings />
          <span>数据操作</span>
        </a-space>
      </template>
      
      <div class="operation-content">
        <!-- 导出区域 -->
        <div class="export-section">
          <a-space direction="vertical" :size="12" fill>
            <div class="section-label">导出数据</div>
            <a-select 
              v-model="exportNodenum" 
              placeholder="选择要导出的章节"
              allow-clear
              style="width: 300px"
            >
              <a-option :value="undefined">全部章节</a-option>
              <a-option :value="0">E0 导入</a-option>
              <a-option :value="1">E1 探寻重复消极思维</a-option>
              <a-option :value="2">E2 认识价值与行动选择</a-option>
              <a-option :value="3">E3 跟消极想法说再见</a-option>
              <a-option :value="4">E4 做想法的旁观者</a-option>
              <a-option :value="5">E5 探寻自我与生活方向</a-option>
              <a-option :value="6">E6 行动指南</a-option>
              <a-option :value="7">E7 结束</a-option>
            </a-select>
            <a-button type="outline" size="large" @click="handleExport">
              <template #icon>
                <icon-download />
              </template>
              导出Excel
            </a-button>
          </a-space>
        </div>
        
        <a-divider direction="vertical" style="height: 120px" />
        
        <!-- 其他操作 -->
        <div class="other-operations">
          <a-space size="large">
            <a-button type="primary" size="large" @click="showImportModal = true">
              <template #icon>
                <icon-upload />
              </template>
              导入Excel
            </a-button>
            
            <a-button status="danger" size="large" @click="handleClearData">
              <template #icon>
                <icon-delete />
              </template>
              清除所有数据
            </a-button>
          </a-space>
        </div>
      </div>
    </a-card>
    
    <!-- 导入弹窗 -->
    <a-modal
      v-model:visible="showImportModal"
      title="导入Excel文件"
      width="600px"
      @cancel="handleImportCancel"
      :footer="false"
    >
      <div class="upload-section">
        <a-upload
          ref="uploadRef"
          :action="uploadAction"
          :headers="uploadHeaders"
          name="excel"
          :show-file-list="true"
          :limit="1"
          :auto-upload="true"
          accept=".xlsx,.xls"
          :before-upload="beforeUpload"
          @success="handleSuccess"
          @error="handleError"
          drag
          class="upload-drag"
        >
          <template #upload-button>
            <div class="upload-area">
              <div class="upload-icon">
                <IconUpload />
              </div>
              <div class="upload-text">
                <p class="upload-title">点击或拖拽文件到此区域上传</p>
                <p class="upload-subtitle">
                  <a-tag color="arcoblue" size="small">支持格式</a-tag>
                  .xlsx、.xls
                  <a-tag color="green" size="small">文件大小</a-tag>
                  不超过10MB
                </p>
              </div>
            </div>
          </template>
        </a-upload>
        
        <div v-if="uploadResult" class="upload-result">
          <a-alert
            :type="uploadResult.success ? 'success' : 'error'"
            :message="uploadResult.message"
            :show-icon="true"
            :closable="true"
            banner
          />
        </div>
        
      </div>
    </a-modal>
    
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { Message, Modal } from '@arco-design/web-vue'
import { 
  IconDownload, 
  IconUpload,
  IconInfoCircle,
  IconFile,
  IconSettings,
  IconDelete
} from '@arco-design/web-vue/es/icon'
import { dataApi } from '../../api'

const uploadRef = ref()
const uploadResult = ref<any>(null)
const showImportModal = ref(false)
const exportNodenum = ref<number | undefined>(undefined)

// 动态上传地址 - 使用API配置
const uploadAction = computed(() => dataApi.getUploadUrl())

// 上传请求的headers - 包含认证信息
const uploadHeaders = computed(() => {
  const token = localStorage.getItem('token')
  return token ? { Authorization: `Bearer ${token}` } : {}
})

const sampleData = [
  { chapter: 1, question: 1, content: '你好，欢迎来到问卷调研系统！', type: 'T', next: 2, needInput: 0, img: '/images/01.png', timer: '' },
  { chapter: 1, question: 2, content: '首先，请告诉我你的性别：', type: 'T', next: 3, needInput: 0, img: '', timer: 30 },
  { chapter: 1, question: 3, content: '我是男性', type: 'C', next: 4, needInput: 0, img: '', timer: '' },
  { chapter: 1, question: 3, content: '我是女性', type: 'C', next: 5, needInput: 0, img: '', timer: '' },
  { chapter: 1, question: 4, content: '请写下你最喜欢的活动类型：', type: 'T', next: 5, needInput: 1, img: '', timer: '' },
  { chapter: 1, question: 5, content: '感谢你的分享！', type: 'T', next: 0, needInput: 0, img: '', timer: '' }
]

const beforeUpload = (file: File) => {
  const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
                  file.type === 'application/vnd.ms-excel'
  
  if (!isExcel) {
    Message.error('只能上传Excel文件！')
    return false
  }
  
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    Message.error('文件大小不能超过10MB！')
    return false
  }
  
  return true
}

const handleSuccess = (response: any) => {
  console.log('上传成功回调:', response)
  
  // Arco Design upload组件可能会包装响应，需要处理不同的响应格式
  let actualResponse = response
  
  // 如果response有response属性，说明被包装了
  if (response.response) {
    actualResponse = response.response
  }
  
  // 如果response有data属性，可能是axios包装的
  if (response.data) {
    actualResponse = response.data
  }
  
  console.log('实际响应数据:', actualResponse)
  
  uploadResult.value = {
    success: actualResponse.success,
    message: actualResponse.message || (actualResponse.success ? '导入成功' : '导入失败')
  }
  
  if (actualResponse.success) {
    Message.success(actualResponse.message || '导入成功')
    // 导入成功后关闭弹窗
    setTimeout(() => {
      showImportModal.value = false
    }, 1500)
  } else {
    Message.error(actualResponse.message || '导入失败')
  }
  
  // 清除上传结果提示
  setTimeout(() => {
    uploadResult.value = null
  }, 5000)
}

const handleImportCancel = () => {
  showImportModal.value = false
  uploadResult.value = null
}

const handleError = (error: any) => {
  console.error('上传失败回调:', error)
  
  let errorMessage = '上传失败，请重试'
  
  // 尝试从不同的位置获取错误信息
  if (error.response?.data?.message) {
    errorMessage = error.response.data.message
  } else if (error.message) {
    errorMessage = error.message
  } else if (typeof error === 'string') {
    errorMessage = error
  }
  
  uploadResult.value = {
    success: false,
    message: errorMessage
  }
  
  Message.error(errorMessage)
  
  // 清除上传结果提示
  setTimeout(() => {
    uploadResult.value = null
  }, 5000)
}

const downloadTemplate = () => {
  // 创建示例数据的Excel文件下载
  const data = [
    ['章节编号', '问题编号', '问题内容', '问题类型', '下一题编号', '需要输入框', '图片路径', '计时器'],
    [1, 1, '你好，欢迎来到问卷调研系统！', 'T', 2, 0, '/images/01.png', ''],
    [1, 2, '首先，请告诉我你的性别：', 'T', 3, 0, '', ''],
    [1, 3, '我是男性', 'C', 4, 0, '', ''],
    [1, 3, '我是女性', 'C', 5, 0, '', ''],
    [1, 4, '请写下你最喜欢的活动类型：', 'T', 5, 1, '', ''],
    [1, 5, '感谢你的分享！', 'T', 0, 0, '', ''],
    ['', '', '', '', '', '', '', ''],
    ['说明：', '', '', '', '', '', '', ''],
    ['章节编号', '数字，表示第几章', '', '', '', '', '', ''],
    ['问题编号', '数字，表示章节内的问题顺序', '', '', '', '', '', ''],
    ['问题内容', '文本，问题或选项的具体内容', '', '', '', '', '', ''],
    ['问题类型', 'T表示系统文本，C表示用户选择选项', '', '', '', '', '', ''],
    ['下一题编号', '数字，用户选择后跳转的问题编号，0表示章节结束', '', '', '', '', '', ''],
    ['需要输入框', '1表示需要输入框，0或空表示不需要（可选）', '', '', '', '', '', ''],
    ['图片路径', '格式：/images/文件名.png，图片需放在public/images/文件夹（可选）', '', '', '', '', '', ''],
    ['计时器', '计时秒数，时间到自动跳转（可选）', '', '', '', '', '', '']
  ]
  
  // 简单的CSV下载实现
  const csvContent = data.map(row => row.join(',')).join('\n')
  const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = '问答脚本导入模板.csv'
  link.click()
  URL.revokeObjectURL(link.href)
}

// 导出Excel
const handleExport = async () => {
  try {
    Message.loading('正在导出数据...')
    
    const response = await dataApi.exportExcel(exportNodenum.value)
    
    // 创建下载链接
    const blob = new Blob([response.data], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    
    // 从响应头获取文件名，如果没有则使用默认名称
    const contentDisposition = response.headers['content-disposition']
    let filename = '问答脚本导出.xlsx'
    if (contentDisposition) {
      const filenameMatch = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/)
      if (filenameMatch && filenameMatch[1]) {
        filename = decodeURIComponent(filenameMatch[1].replace(/['"]/g, ''))
      }
    }
    
    link.download = filename
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    Message.success('导出成功')
  } catch (error: any) {
    console.error('导出失败:', error)
    Message.error(error.response?.data?.message || '导出失败，请重试')
  }
}

// 清除所有数据
const handleClearData = () => {
  Modal.confirm({
    title: '确认清除所有数据？',
    content: '此操作将删除所有问答脚本数据，且不可恢复。请确认是否继续？',
    okText: '确认清除',
    cancelText: '取消',
    okButtonProps: {
      status: 'danger'
    },
    onOk: async () => {
      try {
        const response = await dataApi.clearAllScripts()
        
        if (response.success) {
          Message.success(response.message || '清除成功')
        } else {
          Message.error(response.message || '清除失败')
        }
      } catch (error: any) {
        console.error('清除数据失败:', error)
        Message.error(error.response?.data?.message || '清除数据失败，请重试')
      }
    }
  })
}

</script>

<style scoped>
.import-excel {
  padding: 24px;
}

.instruction-card,
.operation-card {
  margin-bottom: 24px;
  border: 1px solid #e5e6eb;
}

.operation-content {
  padding: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 32px;
}

.export-section,
.other-operations {
  display: flex;
  align-items: center;
}

.section-label {
  font-size: 14px;
  font-weight: 500;
  color: #1d2129;
  margin-bottom: 4px;
}

.instruction-content {
  padding: 4px 0;
}

.format-alert {
  margin-bottom: 20px;
}

.format-list {
  margin-top: 12px;
}

.sample-section {
  margin: 16px 0;
}

.download-section {
  text-align: center;
  margin-top: 16px;
}

.upload-tips {
  margin-top: 20px;
}

.tips-content p {
  margin: 4px 0;
  color: #4e5969;
  font-size: 14px;
}

:deep(.upload-drag .arco-upload-drag) {
  border-radius: 12px;
  border: 2px dashed #c9cdd4;
  background: #fafbfc;
  transition: all 0.3s ease;
}

:deep(.upload-drag .arco-upload-drag:hover) {
  border-color: #165dff;
  background: #f2f6ff;
}

.upload-area {
  padding: 32px;
  text-align: center;
  cursor: pointer;
}

.upload-icon {
  font-size: 48px;
  color: #165dff;
  margin-bottom: 16px;
  display: flex;
  justify-content: center;
}

.upload-title {
  color: #1d2129;
  font-size: 16px;
  font-weight: 500;
  margin: 0 0 12px 0;
}

.upload-subtitle {
  color: #4e5969;
  font-size: 14px;
  margin: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  flex-wrap: wrap;
}

.upload-result {
  margin-top: 16px;
}

.history-list {
  max-height: 400px;
  overflow-y: auto;
}

.history-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 0;
  border-bottom: 1px solid #e5e6eb;
}

.history-item:last-child {
  border-bottom: none;
}

.history-info {
  flex: 1;
}

.history-filename {
  color: #1d2129;
  font-weight: 500;
  margin-bottom: 4px;
}

.history-details {
  color: #86909c;
  font-size: 12px;
  display: flex;
  gap: 16px;
}

.history-status.success {
  color: #00b42a;
}

.history-status.error {
  color: #f53f3f;
}

.empty-history {
  text-align: center;
  padding: 40px 0;
}

.detail-content {
  padding: 16px 0;
}

.detail-item {
  display: flex;
  margin-bottom: 16px;
}

.detail-item label {
  width: 80px;
  color: #4e5969;
  font-weight: 500;
  flex-shrink: 0;
}

.detail-item span {
  color: #1d2129;
}

.detail-message {
  color: #1d2129;
  background: #f7f8fa;
  padding: 8px 12px;
  border-radius: 4px;
  font-size: 14px;
  line-height: 1.5;
}

</style>
